//
//  MMerchantViewController.m
//  NeusoftHBSJSober
//
//  Created by Apple-21 on 15/11/5.
//  Copyright (c) 2015年 com.neusoftsober. All rights reserved.
//

#import "MMerchantViewController.h"
#import "MHomeViewController.h"
#import "MViewUtil.h"
#import "MMerchantMapViewController.h"
#import "MListDataViewController.h"
@interface MMerchantViewController ()<UITableViewDataSource, UITableViewDelegate, UIWebViewDelegate> {

    MViewUtil *viewUtil;
    CGFloat heightOffset;
    MMerchantMapViewController *merchantMapVC;
    MListDataViewController *listDataVC;
}
- (IBAction)backAction:(UIButton *)sender;

@property (weak, nonatomic) IBOutlet UIView *listView;

@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *phoneLabel;
@property (weak, nonatomic) IBOutlet UILabel *distanceLabel;
- (IBAction)noticeMapBtnAction:(UIButton *)sender;
@property (weak, nonatomic) IBOutlet UILabel *tagLabel;
@property (weak, nonatomic) IBOutlet UIButton *noticeBtn;

@property (weak, nonatomic) IBOutlet UITableView *myTabelView;

@property (nonatomic, strong) NSMutableArray *productMutArr;
@property (weak, nonatomic) IBOutlet UIView *merchantView;
@property (weak, nonatomic) IBOutlet UIScrollView *contentScrollView;
@property (weak, nonatomic) IBOutlet UIWebView *merchantWebView;

@end

@implementation MMerchantViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.listView.layer setCornerRadius:3.0];
    [self.listView.layer setMasksToBounds:YES];
    self.productMutArr = [NSMutableArray array];
    self.contentScrollView.backgroundColor = LIGHTGREEN;
    [self.merchantView.layer setCornerRadius:3.0];
    [self.merchantView.layer setMasksToBounds:YES];
    
    viewUtil = [[MViewUtil alloc]init];
    
}
- (void)viewWillAppear:(BOOL)animated {
    
    [self setProductInfo];
    [self _loadMerchantProducts];
    heightOffset = 0.0f;
    
}
-(void)webViewDidFinishLoad:(UIWebView *)webView {

    NSString *meta = [NSString stringWithFormat:@"document.getElementsByName(\"viewport\")[0].content = \"width=%f, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no\"", webView.frame.size.width];
    NSString *fontSize = [[NSString alloc] initWithFormat:@"document.body.style.fontSize=%f",12.0];
    [webView stringByEvaluatingJavaScriptFromString:fontSize];
    [webView stringByEvaluatingJavaScriptFromString:meta];
    [webView stringByEvaluatingJavaScriptFromString:
     @"var script = document.createElement('script');"
     "script.type = 'text/javascript';"
     "script.text = \"function ResizeImages(screentWidth) { "
     "var myimg,oldwidth,oldHeight;"
     "var maxwidth=screentWidth;var scrollHeight=document.body.scrollHeight;" //缩放系数
     "for(i=0;i <document.images.length;i++){"
     "myimg = document.images[i];"
     "if(myimg.width > maxwidth){"
     "oldwidth = myimg.width;"
     "oldHeight = myimg.height;"
     "myimg.width = maxwidth;"
     "myimg.height = oldHeight * (maxwidth/oldwidth);"
     "scrollHeight +=(oldHeight-myimg.height);"
     "}"
     "}"
     "document.body.scrollHeight=scrollHeight+10;"
     "}\";"
     "document.getElementsByTagName('head')[0].appendChild(script);"];
    [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"ResizeImages(%f);",self.merchantWebView.frame.size.width]];
    NSString *he = [webView stringByEvaluatingJavaScriptFromString: @"document.body.scrollHeight"];
    
    heightOffset = [he floatValue] - self.merchantWebView.frame.size.height;
    if (heightOffset < 0) {
        heightOffset = 0;
    }
    
    if (webView == self.merchantWebView) {
        
        
        self.contentScrollView.contentSize = CGSizeMake(self.contentScrollView.contentSize.width, self.contentScrollView.contentSize.height);
        
        self.merchantView.frame = CGRectMake(self.merchantView.frame.origin.x, self.merchantView.frame.origin.y, self.merchantView.frame.size.width, self.merchantView.frame.size.height+heightOffset);
        
        self.merchantWebView.frame = CGRectMake(self.merchantWebView.frame.origin.x, self.merchantWebView.frame.origin.y, self.merchantWebView.frame.size.width, [he floatValue]);
    }
    
    
}
- (void)setProductInfo {

    
    if (self.model) {
        self.nameLabel.text = self.model.companyName;
        self.phoneLabel.text = [NSString stringWithFormat:@"商家电话：%@",self.model.phone];
        self.distanceLabel.text = [NSString stringWithFormat:@"商家地址：%@",self.model.address];
        self.tagLabel.text = [NSString stringWithFormat:@"%@米",self.model.distance];
        
        [self.noticeBtn setTitle:self.model.latitude forState:UIControlStateNormal];
        [self.noticeBtn setTitle:self.model.longtitude forState:UIControlStateHighlighted];
        [self.noticeBtn setTitle:self.model.companyName forState:UIControlStateSelected];
        
        // 商家介绍WebView
        [self.merchantWebView loadHTMLString:self.model.saleManMemo baseURL:[NSURL URLWithString:@"http://www.huobi3j.com"]];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)backAction:(UIButton *)sender {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)noticeMapBtnAction:(UIButton *)sender {
//    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
//    [dict setObject:self.model forKey:self.model.title];
    merchantMapVC = [[MMerchantMapViewController alloc]init];
    merchantMapVC.model = self.model;
    merchantMapVC.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:merchantMapVC animated:YES completion:nil];
}

#pragma mark  tableView
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 65;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.myTabelView.bounds.size.width, 65)];
    headerView.backgroundColor = [UIColor whiteColor];
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(8, 6, self.myTabelView.bounds.size.width, 30)];
    titleLabel.text = @"商家其他价格信息";
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.font = [UIFont fontWithName:nil size:16.0];
    titleLabel.textAlignment = NSTextAlignmentLeft;
    [headerView addSubview:titleLabel];
    
    UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 30, self.myTabelView.bounds.size.width, 35)];
    [headerView addSubview:titleView];
    
    [titleView setBackgroundColor:WHITESMOLKE];
    UILabel *priceLable = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.myTabelView.frame.size.width/3, 35)];
    priceLable.text = @"价格";
    priceLable.textAlignment = NSTextAlignmentCenter;
    priceLable.font = [UIFont fontWithName:nil size:15];
    priceLable.textColor = [UIColor blackColor];
    [titleView addSubview:priceLable];
    
    UILabel *nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.myTabelView.frame.size.width/3, 0, self.myTabelView.frame.size.width/3, 35)];
    nameLabel.text = @"简单描述";
    nameLabel.textAlignment = NSTextAlignmentCenter;
    nameLabel.font = [UIFont fontWithName:nil size:15];
    nameLabel.textColor = [UIColor blackColor];
    [titleView addSubview:nameLabel];
    
    UILabel *descriptionLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.myTabelView.frame.size.width*2/3, 0, self.myTabelView.frame.size.width/3, 35)];
    descriptionLabel.text = @"关键字";
    descriptionLabel.textAlignment = NSTextAlignmentCenter;
    descriptionLabel.font = [UIFont fontWithName:nil size:15];
    descriptionLabel.textColor = [UIColor blackColor];
    [titleView addSubview:descriptionLabel];
    
    return headerView;
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    tableView.frame = CGRectMake(tableView.frame.origin.x, tableView.frame.origin.y, tableView.frame.size.width, self.productMutArr.count*35+65);
   
    CGFloat height = tableView.frame.origin.y + tableView.frame.size.height;
    

    self.merchantView.frame = CGRectMake(self.merchantView.frame.origin.x, height + 10, self.merchantView.frame.size.width, self.merchantView.frame.size.height);
    
    self.contentScrollView.contentSize = CGSizeMake(self.contentScrollView.contentSize.width,tableView.frame.origin.y + tableView.frame.size.height+10 + self.merchantView.frame.size.height);
    
   
    
    return self.productMutArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LIST_DETAL_CELL"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"LIST_DETAL_CELL"];
        UILabel *priceLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, self.myTabelView.bounds.size.width/3, 35)];
        priceLabel.tag = 10;
        priceLabel.font = [UIFont systemFontOfSize:12];
        priceLabel.textAlignment = NSTextAlignmentCenter;
        priceLabel.backgroundColor = [UIColor clearColor];
        priceLabel.textColor = [UIColor colorWithRed:255 green:105.0f/255.0f blue:0.0f alpha:1.0f];
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREENWIDTH/3-10, 0, self.myTabelView.bounds.size.width/3, 35)];
        titleLabel.tag = 11;
        titleLabel.font = [UIFont systemFontOfSize:12];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.numberOfLines = 0;
        titleLabel.lineBreakMode =  NSLineBreakByWordWrapping;
        titleLabel.backgroundColor = [UIColor clearColor];
        UILabel *descriptionLabel =[[UILabel alloc] initWithFrame:CGRectMake(2*SCREENWIDTH/3, 0, self.myTabelView.bounds.size.width/3, 35)];
        descriptionLabel.tag = 12;
        descriptionLabel.font = [UIFont systemFontOfSize:12];
        descriptionLabel.textAlignment = NSTextAlignmentCenter;
        descriptionLabel.backgroundColor = [UIColor clearColor];
        [cell.contentView addSubview:priceLabel];
        [cell.contentView addSubview:titleLabel];
        [cell.contentView addSubview:descriptionLabel];
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            
            [cell setSeparatorInset:UIEdgeInsetsZero];
            
        }
        
        if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
            
            [cell setLayoutMargins:UIEdgeInsetsZero];
            
        }
    }
    
    ((UILabel *)[cell.contentView viewWithTag:10]).text =[NSString stringWithFormat:@"%@元",((MListModel *)self.productMutArr[indexPath.row]).price];
    ((UILabel *)[cell.contentView viewWithTag:11]).text = ((MListModel *)self.productMutArr[indexPath.row]).title;
    ((UILabel *)[cell.contentView viewWithTag:12]).text = ((MListModel *)self.productMutArr[indexPath.row]).KName;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    MListModel *model = [[MListModel alloc]init];
    model = [self.productMutArr objectAtIndex:indexPath.row];
    
    listDataVC = [[MListDataViewController alloc]init];
    listDataVC.model = model;
    listDataVC.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:listDataVC animated:YES completion:nil];
    
}
- (void)_loadMerchantProducts
{
    [self.productMutArr removeAllObjects];
    [viewUtil showLoadingText:@"加载商品数据。" targetView:self.view];
    
    [[MListServices sharedClient]getMerchantProductListWithMerchantID:self.model.createUserID comletion:^(NSMutableArray *result){
        [self.productMutArr addObjectsFromArray:result];
        [self.myTabelView reloadData];
        
        
        [viewUtil hideLoadingTextFromTargetView:self.view];
    } failure:^(NSString *error){
        
        [viewUtil hideLoadingTextFromTargetView:self.view];
        [viewUtil showShortDurationMessage:@"商品加载失败。" targetView:self.view];
    }];
    
}
@end
